javascript如何通过云函数触发firestore集合
每当我点击应用程序中的以下按钮时,我想从现有的关注者集合和视频集合中触发一个新集合(时间线集合)
现在的问题是,云函数是从视图日志创建的,但不会创建新集合(时间线集合)
下面是云函数的代码,我将关注者集合和视频集合作为目标,创建一个新的时间线集合。我期待你的帮助
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
exports.onCreateFollower = functions.firestore
.document("/followers/{userId}/userFollowers/{userfollowerId}")
.onCreate(async (snapshot, context) => {
console.log("The Event has Created The Follower", snapshot.id);
const userId = context.params.userId;
const userfollowerId = context.params.userfollowerId;
// 1) Create followed users posts ref
const followedUserVideosCollection = admin
.firestore()
.collection("videos")
.doc(userId)
.collection("userVideos");
// 2) Create following user's timeline ref
const timelineVideosCollection = admin
.firestore()
.collection("timeline")
.doc(userfollowerId)
.collection("timelinePosts");
// 3) Get followed users posts
const querySnapshot = await followedUserVideosCollection.get();
// 4) Add each user post to following user's timeline
querySnapshot.forEach(doc => {
if (doc.exists) {
const videoId = doc.id;
const videoData = doc.data();
timelineVideosCollection.doc(videoId).set(videoData);
}
});
});
# 1 楼答案
我找出了错误“querySnapshot.forEach不是函数”的原因。根据to this answer,您需要首先查询集合,因为
get()
返回的是文档而不是快照。下面是一个示例代码(请参见步骤3):解决方案是创建一个过滤器,并确保您要查找的文档与过滤器匹配。例如,子集合
userVideos
中的文档应该有一个名为id
的字段,其值为0您可能需要重新构建数据库以修复我在其中放置注释的行,但这段代码应该编写
timeline
集合